<template>
  <div class="checkout-container">
    <div class="checkout-header">
      <h2>确认订单</h2>
    </div>

    <!-- 收货地址 -->
    <div class="section address-section">
      <address-selector
        v-model="selectedAddress"
        title="收货地址"
        :showAddButton="true"
      />
    </div>

    <!-- 订单商品 -->
    <div class="section order-section">
      <h3>订单商品</h3>
      <div class="product-list">
        <div v-for="item in checkoutItems" :key="item.id" class="product-item">
          <img :src="fileBaseUrl() + item.imageUrls.split(',')[0]" :alt="item.name" class="product-image">
          <div class="product-info">
            <h4>{{ item.productName }}</h4>
            <p class="product-desc">{{ item.englishName }}</p>
            <div class="product-price">
              <span class="price">¥{{ item.price.toFixed(2) }}</span>
              <span class="quantity">x{{ item.quantity }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 支付方式 -->
    <div class="section payment-section">
      <h3>支付方式</h3>
      <div class="payment-methods">
        <div v-for="method in paymentMethods" :key="method.id" class="payment-method"
          :class="{ 'active': selectedPayment === method.id }" @click="selectPayment(method.id)">
          <el-icon class="payment-icon">
            <component :is="method.icon" />
          </el-icon>
          <span>{{ method.name }}</span>
        </div>
      </div>
    </div>

    <!-- 订单金额 -->
    <div class="section amount-section">
      <div class="amount-item">
        <span>商品总额</span>
        <span>¥{{ totalAmount.toFixed(2) }}</span>
      </div>

      <div class="amount-item total">
        <span>应付总额</span>
        <span class="final-amount">¥{{ (totalAmount).toFixed(2) }}</span>
      </div>
    </div>

    <!-- 提交订单 -->
    <div class="checkout-footer">
      <div class="total-info">
        实付款：<span class="final-amount">¥{{ (totalAmount).toFixed(2) }}</span>
      </div>
      <el-button type="primary" size="large" @click="submitOrder" :loading="submitting">
        提交订单
      </el-button>
    </div>

     <!-- 地址编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="addressForm" :rules="rules" ref="addressFormRef" label-width="100px">
        <el-form-item label="收货人" prop="recipientName">
          <el-input v-model="addressForm.recipientName"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="addressForm.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <area-selector v-model="addressForm.region" :regionData="regionData" :codeToText="codeToText" />
        </el-form-item>
        <el-form-item label="详细地址" prop="streetAddress">
          <el-input type="textarea" v-model="addressForm.streetAddress"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="back()">取 消</el-button>
          <el-button type="primary" @click="saveAddress">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import {fileBaseUrl} from '@/apis/files'
import {addOrder} from '@/apis/order'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import AddressSelector from '@/components/AddressSelector.vue'
import { regionData, provinceAndCityData, codeToText } from 'element-china-area-data'
import { useOrderStore } from '@/stores/orderStore'

const orderStore = useOrderStore()
const user = ref(localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {})
const checkoutItems = ref([])
const selectedAddress = ref('')
const selectedPayment = ref('alipay')
const submitting = ref(false)

onMounted(async () => {
  // 初始化结算商品
  initCheckoutItems()
  if (!checkoutItems.value.length) {
    ElMessage.error('未找到结算商品信息')
    router.push('/shopping')
    return
  }
})

// 初始化结算商品
const initCheckoutItems = () => {
  const items = localStorage.getItem('checkoutItems')
  if (items) {
    const parsedItems = JSON.parse(items)
    checkoutItems.value = parsedItems
  } else {
    checkoutItems.value = []
  }
}

const totalAmount = computed(() => {
  return checkoutItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
})

const handleAddAddress = () => {
  // 处理添加地址
  ElMessage.info('添加地址功能开发中')
}

const selectPayment = (id) => {
  selectedPayment.value = id
}

// 模拟数据
const addresses = ref([])

const paymentMethods = ref([
  { id: 'alipay', name: '支付宝', icon: 'Money' },
  { id: 'wechat', name: '微信支付', icon: 'ChatDotRound' }
])

// 创建订单
const submitOrder = async () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  const orderData = {
    userId: user.value.userInfo.userId,
    orderAmount: totalAmount.value,
    addressId: selectedAddress.value,
    paymentMethod: selectedPayment.value,
    orderStatus: '待支付',
    // 添加订单项列表
    orderItemList: checkoutItems.value.map(item => ({
      productId: item.productId,
      productName: item.productName,
      quantity: item.quantity,
      price: item.price
    }))
  }
  submitting.value = true
  try {
    const res = await addOrder(orderData)
    if (res.code === '0') {
      localStorage.removeItem('checkoutItems')
      ElMessage.success('下单成功')
    } else {
      ElMessage.error(res.msg || '订单创建失败')
    }

  } catch (error) {
    throw error
  } finally {
    submitting.value = false
  }
}

</script>

<style scoped>
.checkout-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
}

.checkout-header {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.checkout-header h2 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.section {
  margin-bottom: 30px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section h3 {
  font-size: 18px;
  color: #333;
  margin: 0 0 20px 0;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.address-item {
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.address-item:hover {
  border-color: #409EFF;
}

.address-item.active {
  border-color: #409EFF;
  background: #f0f9ff;
}

.contact {
  margin-bottom: 8px;
}

.name {
  font-weight: bold;
  margin-right: 15px;
}

.phone {
  color: #666;
}

.detail {
  color: #666;
  font-size: 14px;
}

.check-icon {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #409EFF;
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.product-item {
  display: flex;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 6px;
}

.product-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.product-info {
  flex: 1;
}

.product-info h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.product-desc {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.product-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.quantity {
  color: #666;
}

.payment-methods {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.payment-method {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.payment-method:hover {
  border-color: #409EFF;
}

.payment-method.active {
  border-color: #409EFF;
  background: #f0f9ff;
}

.payment-icon {
  margin-right: 10px;
  font-size: 20px;
}

/* .amount-section {
  background: #fafafa;
} */

.amount-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  color: #666;
}

.amount-item.total {
  margin-top: 10px;
  padding-top: 15px;
  border-top: 1px solid #eee;
  font-weight: bold;
  color: #333;
}

.final-amount {
  color: #f56c6c;
  font-size: 20px;
}

.checkout-footer {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 15px 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.total-info {
  font-size: 16px;
}

@media (max-width: 768px) {
  .checkout-container {
    padding: 10px;
  }

  .section {
    padding: 15px;
  }

  .address-list,
  .payment-methods {
    grid-template-columns: 1fr;
  }
}
</style>